<?php
namespace Modules\Order\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Order\Entities\AgentPayRecord;

use Validator;
use ThrowException;
use Auth;
use DB;
use Setting;

class AgentPayRecordController extends Controller
{
    // 详情页
    public function show(Request $req, $uuid)
    {
        $user = Auth::requireLoginUser();

        $item = AgentPayRecord::getEntity([
            'uuid' => $uuid,
            'with'  => ['order.skus', 'user']
        ]);

        $item->checkStatus();

        $info = $item->getInfo([
            'id',
            'uuid',
            'status',
            'order' => [
                'id',
                'uuid',
                'number',
                'product_money_price',
                'product_score_price',
                'pay_money_price',
                'pay_score_price',
                'cover_type',
                'cover_discount',
                'coupon_discount',
                'redpack_discount',
                'carriage',
                'created_at',
                'union_status',
            ],
            'user' => [
                'id',
                'uuid',
                'headimg',
                'name'
            ]
        ]);

        // sku返回
        if ($item->order->type === 'box') {
            $orderSkus =  $item->order->skus;
            $orderSku = $orderSkus->first();
            $box = $orderSku->base_sku->box;

            $info['order']['skus'] = [
                [
                    'title' => $box->title,
                    'number' => $box->number,
                    'thumb' => $box->thumb,
                    'money_price' => $orderSku->money_price,
                    'score_price' => $orderSku->score_price,
                    'discount_money_price' => $orderSku->discount_money_price,
                    'discount_score_price' => $orderSku->discount_score_price,
                    'product_type' => 'box',
                    'product_uuid' => $box->uuid,
                    'total' => $orderSkus->sum('total')
                ]
            ];
        }
        else {
            $info['order']['skus'] = $item->order->skus;
        }

        return [
            'info' => $info
        ];
    }

    // 发起支付
    public  function pay(Request $req, $uuid)
    {
        $user = Auth::requireLoginUser();

        $item = AgentPayRecord::getEntity([
            'uuid' => $uuid
        ]);

        if ($item->status !== 0) {
            ThrowException::Conflcit('此代付暂无法支付');
        }

        // 获取代付订单的支付信息
        $config = $item->getPayConfig($user);

        return [
            'pay_config' => $config
        ];
    }
}
